package com.ncr.travel.appmgr.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

public final class UrlBuilder {
	private Document messageDom = null;
	// private String screenURI = null;
	private String updateURI = null;
	private String productURI = null;
	private String addImageURI = null;
	private String baseURL;

	private UrlBuilder(String configData) {
		String hostPageUrl = GWT.getHostPageBaseURL();
		messageDom = XMLParser.parse(configData);
		NodeList baseURINode = messageDom.getElementsByTagName("BASE-URL");
		if (hostPageUrl.contains("/travel-appmanager-web/")) {
			hostPageUrl = hostPageUrl.replace("/travel-appmanager-web/", "");
		} else {
			hostPageUrl = hostPageUrl.replace("8888/", "8080");
		}
		baseURL = hostPageUrl + baseURINode.item(0).getFirstChild().getNodeValue();
		// NodeList ipAddress = messageDom.getElementsByTagName("SCREEN-URI");
		// screenURI = ipAddress.item(0).getFirstChild().getNodeValue();
		NodeList portNumber = messageDom.getElementsByTagName("SCREEN-UPDATEURI");
		updateURI = portNumber.item(0).getFirstChild().getNodeValue();
		NodeList product = messageDom.getElementsByTagName("PRODUCT-URI");
		productURI = product.item(0).getFirstChild().getNodeValue();
		NodeList addImageNode = messageDom.getElementsByTagName("ADDIMAGEFORMURI");
		addImageURI = hostPageUrl + addImageNode.item(0).getFirstChild().getNodeValue();
	}

	public static UrlBuilder createUrl(String configData) {
		return new UrlBuilder(configData);
	}

	public String getScreenUri(String productName, String productCategory) {
		String uri = "/config/" + productName + "/" + productCategory;
		System.out.println("URI for screen lookup = '" + uri + "'");
		return uri;
	}

	public String getScreenUriForAddImage(long screenID, long graphicsId) {
		String uri = addImageURI + screenID + "/" + graphicsId + "/addNewImageFormHaldler";
		return uri;
	}

	public String getUriForUpdate() {
		return updateURI;
	}

	public String getUriForProductInformation(String userName) {
		return productURI + userName;
	}

	public String getBaseURL() {
		return baseURL;
	}
}
